import Vue from 'vue'
import VueRouter, { RouteConfig, RouterOptions } from 'vue-router'

Vue.use(VueRouter)

const routes: Array<RouteConfig> = [
  {
    path: '/',
    component: () => import('@/views/home.vue'),
  },
  {
    path: '/login',
    component: () => import('@/views/login/login.vue'),
  },
  {
    path: '/register',
    component: () => import('@/views/register/register.vue'),
  },
  {
    path: '/backend/login',
    component: () => import('@/views-backend/login/login.vue'),
  },
  {
    path: '/404',
    name: 'notFound',
    component: () => import('@/components/404/404.vue'),
  },
  {
    path: '*',
    redirect: '/404',
  },
]

const options: RouterOptions | undefined = {
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
}

let router = new VueRouter(options)

/**
 * 添加路由
 * @param menus 菜单
 */
export function addRouters(menus: Array<IMenu>) {
  const routers = menuToRouter(menus)

  for (let i in routers) {
    router.addRoute('/', routers[i])
  }
}

/**
 * 菜单转成路由
 * @param menus 菜单
 * @returns 路由
 */
function menuToRouter(menus?: Array<IMenu>): Array<RouteConfig> {
  const routers: Array<RouteConfig> = []

  if (!menus || menus.length == 0) {
    return routers
  }

  for (let i = 0; i < menus.length; i++) {
    const menu = menus[i]
    const keys = Object.keys(menu)
    let router: RouteConfig = {} as any

    for (let ki = 0; ki < keys.length; ki++) {
      const key = keys[ki]

      if (key == 'key') {
        router.path = menu.key
      } else if (key == 'children') {
        router.children = menuToRouter(menu.children)
      } else {
        (router as any)[key] = (menu as any)[key]
      }
    }
    routers.push(router)
  }

  return routers
}

export default router
